package com.dailyblue.java.project.bookstore.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.project.bookstore.bean.Book;
import com.dailyblue.java.project.bookstore.bean.ShoppingCart;
import com.dailyblue.java.project.bookstore.exception.ExistException;
import com.dailyblue.java.project.bookstore.mapper.BookMapper;
import com.dailyblue.java.project.bookstore.service.ShoppingCartService;
import com.dailyblue.java.project.bookstore.util.JsonResult;
import com.dailyblue.java.project.bookstore.util.JwtConfig;
import com.dailyblue.java.project.bookstore.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private BookMapper bookMapper;
    private static final String SHOPPING_CART_PREFIX = "SHOPPING_CART:";

    @Override
    public JsonResult add(String bookId, HttpServletRequest request) {
        log.info("开始将'{}'加入购物车", bookId);
        // 加入商品到购物车中
        // 购物车中是否有当前商品
        ValueOperations<String, String> values = stringRedisTemplate.opsForValue();
        String id = JwtConfig.getMemberIdByJwtToken(request);
        String json = values.get(SHOPPING_CART_PREFIX + id);
        log.info("userId:{},它的购物车:{}", id, json);
        // 第一次添加购物车
        if (json == null || json.trim().equals("")) {
            // 直接添加
            List<ShoppingCart> carts = new ArrayList<>();
            ShoppingCart sc = new ShoppingCart(id, bookId, 1);
            Book book = bookMapper.selectById(bookId);
            sc.setPrice(book.getPrice());
            sc.setBookName(book.getName());
            sc.setImageName(book.getImageName());
            sc.setPublisher(book.getPublisher());
            carts.add(sc);
            values.set(SHOPPING_CART_PREFIX + id, JSONArray.toJSONString(carts));
            return ResultTool.success();
        }
        List<ShoppingCart> carts = JSONArray.parseArray(json, ShoppingCart.class);
        int index = checkBookIdExist(carts, bookId);
        if (index != -1) {
            // 存在了
            throw new ExistException("商品已经存在");
        }
        // 加入购物车
        ShoppingCart sc = new ShoppingCart(id, bookId, 1);
        Book book = bookMapper.selectById(bookId);
        sc.setPrice(book.getPrice());
        sc.setBookName(book.getName());
        sc.setImageName(book.getImageName());
        sc.setPublisher(book.getPublisher());
        carts.add(sc);
        values.set(SHOPPING_CART_PREFIX + id, JSONArray.toJSONString(carts));
        return ResultTool.success();
    }

    @Override
    public JsonResult find(HttpServletRequest request) {
        ValueOperations<String, String> values = stringRedisTemplate.opsForValue();
        String id = JwtConfig.getMemberIdByJwtToken(request);
        String json = values.get(SHOPPING_CART_PREFIX + id);
        if (json == null || json.trim().equals("")) {
            return ResultTool.fail("购物车为空！");
        }
        List<ShoppingCart> carts = JSONArray.parseArray(json, ShoppingCart.class);
        return ResultTool.success(carts);
    }

    @Override
    public JsonResult changeNumber(String bookId, HttpServletRequest request, int number) {
        JsonResult<List<ShoppingCart>> result = find(request);
        List<ShoppingCart> carts = result.getData();
        int index = checkBookIdExist(carts, bookId);
        if (index < 0) {
            throw new ExistException("没有这本图书");
        }
        carts.get(index).setNumber(number);
        ValueOperations<String, String> values = stringRedisTemplate.opsForValue();
        String id = JwtConfig.getMemberIdByJwtToken(request);
        values.set(SHOPPING_CART_PREFIX + id, JSONArray.toJSONString(carts));
        return ResultTool.success();
    }

    @Override
    public JsonResult remove(HttpServletRequest request, String... bookId) {
        JsonResult<List<ShoppingCart>> result = find(request);
        List<ShoppingCart> carts = result.getData();
        for (String b : bookId) {
            int index = checkBookIdExist(carts, b);
            if (index > -1) {
                carts.remove(index);
            }
        }
        ValueOperations<String, String> values = stringRedisTemplate.opsForValue();
        String id = JwtConfig.getMemberIdByJwtToken(request);
        values.set(SHOPPING_CART_PREFIX + id, JSONArray.toJSONString(carts));
        return ResultTool.success();
    }

    private int checkBookIdExist(List<ShoppingCart> carts, String bookId) {
        int index = -1;
        int i = 0;
        for (ShoppingCart s : carts) {
            if (s.getBookId().equals(bookId)) {
                index = i;
                break;
            }
            i++;
        }
        return index;
    }
}
